package rtool

import (
	"strings"
	"sync"
)

// DeletePrev0 删除掉前面的0，或多个0
func DeletePrev0(s string) string {
	for i := 0; i < len(s); i++ {
		if s[i] == '0' {
			continue
		}
		return s[i:]
	}
	return ""
}

// DeleteAllSpace 删除掉空格，tab，回车，换行
func DeleteAllSpace(s string) string {
	var temp = make([]byte, len(s))
	var index = 0
	for i := 0; i < len(s); i++ {
		if s[i] < 0x80 {
			switch s[i] {
			case ' ', '\t', '\n', '\v', '\f', '\r':
				continue
			}
		}
		temp[index] = s[i]
		index++
	}
	s = strings.ReplaceAll(string(temp[:index]), string(0x85), "")
	s = strings.ReplaceAll(s, string(0xA0), "")
	return s
}

// DeleteAllSpaceReplace 删除掉空格，tab，回车，换行；采用Replace的方式
func DeleteAllSpaceReplace(s string) string {
	s = strings.ReplaceAll(s, " ", "")
	s = strings.ReplaceAll(s, "\t", "")
	s = strings.ReplaceAll(s, "\n", "")
	s = strings.ReplaceAll(s, "\v", "")
	s = strings.ReplaceAll(s, "\f", "")
	s = strings.ReplaceAll(s, "\r", "")
	s = strings.ReplaceAll(s, string(0x85), "")
	s = strings.ReplaceAll(s, string(0xA0), "")
	return s
}

// DeleteRepeat 删除重复项，不改变元素顺序
func DeleteRepeat[T IntUintString](src []T) []T {
	var tempMap = sync.Map{}
	var rt []T
	for _, d := range src {
		if _, ok := tempMap.Load(d); ok {
			continue
		}
		tempMap.Store(d, byte(1))
		rt = append(rt, d)
	}
	return rt
}

// DeleteRepeatVMap 删除重复项，map随机元素的顺序
func DeleteRepeatVMap[T IntUintString](src []T) []T {
	var tempMap = make(map[T]byte)
	for _, d := range src {
		tempMap[d] = 0
	}
	var rt = make([]T, 0, len(src))
	for k := range tempMap {
		rt = append(rt, k)
	}
	return rt
}

// DeleteRepeatAndShuffle 删除重复项，然后使用洗牌算法打乱顺序
func DeleteRepeatAndShuffle[T IntUintString](src []T) []T {
	length := len(src)
	if length <= 0 || length == 1 {
		return src
	}
	for i := 0; i < length; i++ {
		index := randSource.Intn(length)
		src[i], src[index] = src[index], src[i]
	}
	return src
}

// DeleteRepeatAndEmpty 删除重复项和空字符串项，不改变元素顺序
func DeleteRepeatAndEmpty(src []string) []string {
	var tempMap = sync.Map{}
	var rt []string
	for _, d := range src {
		if d == "" {
			continue
		}
		if _, ok := tempMap.Load(d); ok {
			continue
		}
		tempMap.Store(d, byte(1))
		rt = append(rt, d)
	}
	return rt
}

// DeleteRepeatAndZero 删除重复项和0值项，不改变元素顺序
func DeleteRepeatAndZero(src []int) []int {
	var tempMap = sync.Map{}
	var rt []int
	for _, d := range src {
		if d == 0 {
			continue
		}
		if _, ok := tempMap.Load(d); ok {
			continue
		}
		tempMap.Store(d, byte(1))
		rt = append(rt, d)
	}
	return rt
}

// DeleteLengthLimit 删除掉长度不符合要求的
func DeleteLengthLimit(src []string, minLength int, maxLength int) []string {
	var rt []string
	for _, d := range src {
		if len(d) < minLength || len(d) > maxLength {
			continue
		}
		rt = append(rt, d)
	}
	return rt
}
